#include "newexpense.h"
#include "ui_newexpense.h"
#include<QtSql/QSqlQuery>
#include<QDateTime>
#include<QDesktopWidget>
#include<QMessageBox>
#include<QDebug>
#include<QFile>
//This class allows to create new expense record
NewExpense::NewExpense(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::NewExpense)
{

    ui->setupUi(this);

    QRect innersize=QApplication::desktop()->availableGeometry(this);
    ui->scrollArea->setGeometry(0,0,(innersize.width()),(innersize.height()));
    ui->verticalLayout->addSpacing(15);
    int fontSize=10;
    ui->label->setFont(QFont("lucida",fontSize,QFont::Normal,FALSE));
    ui->label_2->setFont(QFont("lucida",(fontSize-2),QFont::Normal,FALSE));
    ui->label_3->setFont(QFont("lucida",(fontSize-2),QFont::Normal,FALSE));
    ui->label_4->setFont(QFont("lucida",(fontSize-2),QFont::Normal,FALSE));
    ui->label_5->setFont(QFont("lucida",(fontSize-2),QFont::Normal,FALSE));
    ui->label_6->setFont(QFont("lucida",(fontSize-2),QFont::Normal,FALSE));
    ui->lineEdit_amt->setFont(QFont("lucida",(fontSize-2),QFont::Normal,FALSE));
    ui->textEdit_note->setFont(QFont("lucida",(fontSize-2),QFont::Normal,FALSE));
    ui->comboBox_acc->setFont(QFont("lucida",(fontSize-2),QFont::Normal,FALSE));
    ui->comboBox_cat->setFont(QFont("lucida",(fontSize-2),QFont::Normal,FALSE));
    ui->dateEdit->setFont(QFont("lucida",(fontSize-2),QFont::Normal,FALSE));
    ui->comboBox_cat->setFocus();
    ui->lineEdit_amt->setValidator(new QDoubleValidator(this));

    QAction* backAction = new QAction( tr("Back"), this );
     backAction->setSoftKeyRole( QAction::NegativeSoftKey );
     connect(backAction, SIGNAL(triggered()), this, SLOT(back()));
     addAction( backAction );


     ui->dateEdit->setDate(QDate::currentDate());//Set current date

    if(db.db_connect())
     {

            QSqlQuery q;
            if(q.exec(QString("select name from account_table")))
            {
                while(q.next())
                ui->comboBox_acc->addItem(q.value(0).toString(),Qt::UserRole);

            }//Combo box with all available accounts

            if(q.exec(QString("select category_name from category_table")))
            {
                while(q.next())
                ui->comboBox_cat->addItem(q.value(0).toString(),Qt::UserRole);
            }//Combo box with all available categories


         db.db_close();
     }
}

NewExpense::~NewExpense()
{
    delete ui;

}
void NewExpense::back()
{
    (new expense)->show();
}

void NewExpense::on_dateEdit_dateChanged(QDate date)
{
    dt=date;
}

void NewExpense::on_save_clicked()
{
    if(((ui->lineEdit_amt->text().compare(""))==0)||(ui->lineEdit_amt->text().toDouble()<=0))
        QMessageBox::warning(0,"Warning !","Please check the amount");
    else if(((ui->comboBox_acc->currentText().compare(""))==0)||((ui->comboBox_cat->currentText().compare(""))==0))
        QMessageBox::warning(0,"Warning !","Please check the account and category");
    else
    {
    QString note=ui->textEdit_note->toPlainText();
    QString acc=ui->comboBox_acc->currentText();
    QString cat=ui->comboBox_cat->currentText();
    double amt=ui->lineEdit_amt->text().toDouble();
    QDate d=ui->dateEdit->date();
    QString dt_string=d.toString();
    //QDateTime d=QDateTime::fromString(dt.toString(),"ddd MMM dd hh:mm:ss yyyy");


    int id=0;
    double expAmt=0,budget;
    if(db.db_connect())
    {
        QSqlQuery q;
        if(q.exec(QString("update account_table set account_amt=account_amt-%1,expense_amt=expense_amt+%2 where name='%3'").arg(amt).arg(amt).arg(acc)))
        {
            qDebug()<<"Updated";
            //Debit expense amount from account

         if(q.exec(QString("select account_id,budget_amt,expense_amt from account_table where name='%1'").arg(acc)))
        {
            q.next();
            id=q.value(0).toInt();
            budget=q.value(1).toDouble();
            expAmt=q.value(2).toDouble();
            qDebug()<<budget;
            if(budget!=0)//if some budget is assigned
            {

                if(expAmt>budget)//IF total expnse amount exceeds budget
                    QMessageBox::information(0,"Warning !",QString("Total amount of expenses exceeds budget assigned to '%1' account").arg(acc));
            }

        q.prepare(QString("insert into expense_table(exp_amt,note,exp_date,acc_id,cat_name) values(?,?,?,?,?)"));
        q.addBindValue(amt);
        q.addBindValue(note);
        q.addBindValue(d);
        q.addBindValue(id);
        q.addBindValue(cat);
        if(q.exec())
        {
            QMessageBox::information(0,"Success !","Expense added !");
           (new expense)->show();
       }

    }
    }
       else
           QMessageBox::information(0,"Error !","Sorry ,can not add new expense");
      /* if(q.exec(QString("select * from expense_table where exp_date>'%1'").arg(dt_string)))
       {
        q.next();
        qDebug()<<q.value(3).toString();
       }
        if(q.exec(QString("drop table expense_table")))
            qDebug()<<"Deleted";*/

       db.db_close();
    }//Connection

    }


}


